package com.lzj.server.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.lzj.server.entity.video.UserInfo;
import com.lzj.server.service.UserService;
import com.lzj.server.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/vimi/user")
@Tag(name = "用户登录模块")
@Validated
public class UserBaseController {
    private final UserService userService;

    UserBaseController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("/get")
    @Operation(summary = "获取用户信息")
    public Result<UserInfo> getUser() {
        UserInfo user = userService.getById(StpUtil.getLoginIdAsLong());
        user.setPassword(null);
        return Result.success(user);
    }


    @GetMapping("/login")
    @Operation(summary = "用户登录")
    public Result<?> userLogin(@RequestParam @NotBlank String email, @RequestParam @NotBlank String password) {
        String token = userService.login(email, password);
        if (ObjUtil.isNull(token)) {
            return Result.error("登录失败");
        }
        log.info("登录成功, token: {}", token);
        return Result.success(token);
    }

    @Operation(summary = "查询登录状态")
    @GetMapping("/isLogin")
    public Result<?> isLogin() {
        return Result.success("是否登录：" + StpUtil.isLogin());
    }

    @Operation(summary = "查询 Token 信息")
    @GetMapping("/tokenInfo")
    public Result<?> tokenInfo() {
        return Result.success(StpUtil.getTokenInfo());
    }

    @Operation(summary = "注销")
    @GetMapping("/logout")
    public Result<?> logout() {
        StpUtil.logout();
        return Result.success("注销成功");
    }

    @SaIgnore
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<String> register(@RequestBody UserInfo user) {
        if (!userService.register(user)) {
            return Result.error("注册失败");
        }
        return Result.success(("注册成功"),null);
    }

    @SaIgnore
    @Operation(summary = "校验邮箱验证码")
    @PostMapping("/checkCode")
    public Result<Void> checkCode(@RequestParam @NotBlank String code, @RequestParam @NotBlank @Email String email) {
        if (!userService.checkCode(code, email)) {
            return Result.error("验证码错误");
        }
        return Result.success("验证码正确", null);
    }

    @SaIgnore
    @Operation(summary = "找回密码")
    @PostMapping("/findPassword")
    public Result<Void> findPassword(@RequestBody @Validated UserInfo user) {
        if (!userService.findPassword(user)) {
            return Result.error("找回密码失败");
        }
        return Result.success("找回密码成功", null);
    }
}
